<!DOCTYPE html>
<html lang="zh-cmn-Hans" prefix="og: http://ogp.me/ns#" class="han-init">
<head>
  <meta charset="utf-8">
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <link rel="icon" href="http://upeng.github.io/favicon.ico">
  <title>upeng</title>
  <link rel="stylesheet" href="/css/style.css">
  <link rel="stylesheet" href="/lib/fancybox/jquery.fancybox-1.3.4.css">
  <!--在这里倒入jquery 方便处理部分页面的jquery-->
  <script src="https://cdn.staticfile.org/jquery/1.7/jquery.min.js" type="text/javascript" ></script>
</head>

<body>
	<header class="site-header navfixed-false">
  <div class="container">
      <h1><a href="/" title="upeng"><span class="octicon octicon-mark-github"></span> upeng</a></h1>
      <nav class="site-header-nav" role="navigation">
        
              
              <a href="/"  class=" site-header-nav-item hvr-underline-from-center" title="Home">Home</a>
        
              
              <a href="/categories/"  class=" site-header-nav-item hvr-underline-from-center" title="Categories">Categories</a>
        
              
              <a href="/bookmark/"  class=" site-header-nav-item hvr-underline-from-center" title="Bookmark">Bookmark</a>
        
              
              <a href="http://shareup.sinaapp.com"  class=" site-header-nav-item hvr-underline-from-center" title="Share">Share</a>
        
              
              <a href="/about/"  class=" site-header-nav-item hvr-underline-from-center" title="About">About</a>
        
      </nav>
  </div>
</header>

	
<section class="collection-head geopattern" data-pattern-id="laravel基础任务学习清单" >
    <div class="container">
        <div class="collection-title">
            <h1 class="collection-header">
                laravel基础任务学习清单
            </h1>
            
                <div class="collection-info">
                    <span class="meta-info">
                        <span class="octicon octicon-calendar"></span>
                        <time datetime="2016-08-15T14:24:32.000Z" itemprop="datePublished">2016-08-15</time>
                    </span>
                    
                        <span class="meta-info">
                            <span class="octicon octicon-file-directory"></span>
                            <a href='/categories/PHP/' title=''>PHP</a>
                        </span>
                    
                </div>
            
        </div>
    </div>
</section>
	<section class="container">
    <div class="columns">
        <!-- -->
        <div class="column three-fourths">
            <article class="article-content markdown-body">
                <h2 id="关于Restful路由"><a href="#关于Restful路由" class="headerlink" title="关于Restful路由"></a>关于Restful路由</h2><p><code>Route::resource(&#39;task&#39;, &#39;TaskController&#39;);</code><br>产生多条路由，<code>POST/DELTE/PUT/GET</code>，对应着<code>TaskController</code>的各个方法；<br>对于laravel5.2，使用 <code>php artisan make:controller TaskController --resource</code>可产生默认的多种方法<br>通过<code>php artisan route:list</code>可以显示已经注册的路由列表</p>
<p><img src="https://raw.githubusercontent.com/upeng/upeng.github.io/master/image/laravel-route-list.png" alt="laravel-route-list"></p>
<a id="more"></a>
<h2 id="表单验证"><a href="#表单验证" class="headerlink" title="表单验证"></a>表单验证</h2><blockquote>
<p>store、update方法常使用</p>
</blockquote>
<p>基地控制器<code>Controller</code>内使用了<code>ValidatesRequests</code>这个<code>trait</code>，因此他为所有的控制器都提供了方便的<code>validate</code>验证方法。</p>
<blockquote>
<p>调研了解trait机制，为什么TestController use了这个trait，TestController 就可以使用ValidatesRequests的validate方法</p>
</blockquote>
<h3 id="最原始的表单验证（Controller中）"><a href="#最原始的表单验证（Controller中）" class="headerlink" title="最原始的表单验证（Controller中）"></a>最原始的表单验证（Controller中）</h3><p>validate方法会验证接受HTTP传入的请求与验证规则，如果验证通过，我们的代码才会继续向下运行。如果验证失败会抛出异常错误返回给用户。</p>
<pre><code>public function store(Request $request)
{
    //验证用户请求
    $this-&gt;validate($request,[
        &#39;name&#39; =&gt; &#39;required&#39;,
        &#39;content&#39; =&gt; &#39;required|min:5&#39;,
    ]);

    //通过验证，保存至数据库
    Task::create($request);
}
</code></pre><p><strong>说明</strong>：我们将验证规则传递到<code>validate</code>方法中，如果验证失败，则自动生成一个对应的响应。并将验证的错误提醒闪存至<code>session</code>，也就是<code>$errors</code>。当验证失败时，用户将被重定向到我们的控制器 <code>create</code>方法，让我们在视图中显示错误的消息：</p>
<pre><code>@if (count($errors) &gt; 0)
    &lt;div class=&quot;alert alert-danger&quot;&gt;
        &lt;ul&gt;
            @foreach ($errors-&gt;all() as $error)
            &lt;li&gt;{{$error}}&lt;/li&gt;
        &lt;/ul&gt;
    &lt;/div&gt;
@endif
</code></pre><p><strong>补充</strong>：正常情况下我们想要把错误显示在对应的字段旁边，而不是一起显示在一个列表中；我们打印<code>session</code>中的<code>$errors-&gt;all()</code>是数字索引数组;</p>
<blockquote>
<p>要查看特定字段的第一个错误消息【比较常见的场景】</p>
</blockquote>
<p><strong>方法如下：</strong></p>
<pre><code>@if ($errors-&gt;has(&#39;name&#39;))
$errors-&gt;first(&#39;name&#39;);
@endif

@if ($error-&gt;has(&#39;content&#39;))
$error-&gt;first(&#39;content&#39;);
@endif
</code></pre><blockquote>
<p>我们想要得到一个字段对应的所有error</p>
</blockquote>
<p><strong>方法如下</strong>：</p>
<pre><code>foreach ($error-&gt;get(&#39;content&#39;) as $message)
{
    //
}
</code></pre><h3 id="表单请求验证，自定义请求类"><a href="#表单请求验证，自定义请求类" class="headerlink" title="表单请求验证，自定义请求类"></a>表单请求验证，自定义请求类</h3><blockquote>
<p>php artisan make request TaskFormReuest;</p>
</blockquote>
<p>这时会在<code>Http/Requests</code>目录生成<code>TaskFormReuest.php</code>,修改<code>rules</code>方法，</p>
<pre><code>//权限判断
public function authorize()
{
    return true;
}

//验证规则
public function rules()
{
    return [
        &#39;name&#39; =&gt; &#39;required|min:5&#39;,
    ];
}

//也可以自定义message方法
public function messages()
{
    return [
        &#39;title.required&#39; =&gt; &#39;标题是必填的&#39;,
        &#39;body.required&#39;  =&gt; &#39;消息是必填的&#39;,
    ];
}

//messages还可以这样动态设置
public function messages()
{
    return [
        &#39;required&#39; =&gt; &#39;:attribute 是必填字段&#39;,
        &#39;min&#39;    =&gt; &#39;:attribute 长度不小于 :min&#39;,
    ];
}
</code></pre><h3 id="手动创建验证程序"><a href="#手动创建验证程序" class="headerlink" title="手动创建验证程序"></a>手动创建验证程序</h3><p>不使用validatesRequests的validate方法<br>我们可以use Validator类，手动创建一个validator实例，并通过Validator::make()生成一个新的validator</p>
<pre><code>use Validator;
...
public function store(Request $request)
{
    $validator = Validtor::make($request-&gt;all(),[
        &#39;name&#39; =&gt; &#39;requeire&#39;,
        &#39;content&#39; =&gt; &#39;require|min:6&#39;,
    ]);

    if ($validator-&gt;fails())
    {
        return redirect()-&gt;action(&#39;TaskController@index&#39;)
        -&gt;withErrors($validator)
                -&gt;withInput();
    }
}
</code></pre><p><strong>注</strong>：<code>Validator::make($param1, $param2)</code>，其中<code>$param1</code>是验证的数据，<code>$params</code>是规则</p>
<h2 id="model操作"><a href="#model操作" class="headerlink" title="model操作"></a>model操作</h2><p>增：</p>
<pre><code>1. Task::create($request);
2. 
$task = new Task();
$task-&gt;name = $request-&gt;name;
$task-&gt;created_at = Carbon::now();
$task-&gt;save();
</code></pre><p>删：</p>
<pre><code>1.Task::destroy($id);
2.Task::findOrFail($id)-&gt;delete();
</code></pre><p>改:</p>
<pre><code>Task::update($request, $id);
</code></pre><p>查：</p>
<pre><code>1.Task::all();
2.Task::where()-&gt;get();
3.Task::orderBy(&#39;created_at&#39;, &#39;desc&#39;)-&gt;get();
</code></pre><h2 id="factory工厂模型使用"><a href="#factory工厂模型使用" class="headerlink" title="factory工厂模型使用"></a>factory工厂模型使用</h2><ul>
<li><code>Task Model</code>中设置  <code>protected $fillable = [&#39;name&#39;, &#39;created_at&#39;]</code>;</li>
<li><p><code>datebase/factories/ModelFactory.php</code>新增</p>
<pre><code>$factory-&gt;define(App\Task::class, function (Faker\Generator $faker) {
  return [
      &#39;name&#39; =&gt; $faker-&gt;sentence,
      &#39;created_at&#39; =&gt; Carbon\Carbon::now(),
  ];
});
</code></pre></li>
<li><p><code>php artisan tinker</code></p>
<pre><code>namespace App;
factory(App\Task::class,5)-&gt;create();
</code></pre></li>
</ul>

            </article>
            
                <div class="share">
                    <!--开启分享-->
<div class="share-component" data-disabled="google,twitter,facebook" data-description="关于Restful路由Route::resource(..."></div>

<script src="/js/share.min.js"></script>

                </div>    
            
            
                
<div class="comments">
	<div class="ds-thread" data-thread-key="laravel-basic" data-title="laravel基础任务学习清单" data-url="http://upeng.github.io/2016/08/15/laravel-basic/"></div>
	<script type="text/javascript">
	var duoshuoQuery = {short_name:"upeng"};
		(function() {
			var ds = document.createElement('script');
			ds.type = 'text/javascript';ds.async = true;
			ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
			ds.charset = 'UTF-8';
			(document.getElementsByTagName('head')[0]
			 || document.getElementsByTagName('body')[0]).appendChild(ds);
		})();
	</script>
</div>

            
        </div>
        <div class="column one-fourth">
            
                
                


<h3>Post Directory</h3>

<div id="post-directory-module">
	<section class="post-directory">
		<p><strong class="toc-title">文章目录</strong></p>
		<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#关于Restful路由"><span class="toc-text">关于Restful路由</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#表单验证"><span class="toc-text">表单验证</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#最原始的表单验证（Controller中）"><span class="toc-text">最原始的表单验证（Controller中）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#表单请求验证，自定义请求类"><span class="toc-text">表单请求验证，自定义请求类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#手动创建验证程序"><span class="toc-text">手动创建验证程序</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#model操作"><span class="toc-text">model操作</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#factory工厂模型使用"><span class="toc-text">factory工厂模型使用</span></a></li></ol>
	</section>
</div>
            
        </div>
    </div>
</section>

<footer class="container">
    <div class="site-footer" role="contentinfo">
        <div class="copyright left mobile-block">
                © 2016
                <span title="yupeng">yupeng</span>
                <a href="javascript:window.scrollTo(0,0)" class="right mobile-visible">TOP</a>
        </div>

        <ul class="site-footer-links right mobile-hidden">
            <li>
                <a href="javascript:window.scrollTo(0,0)" >TOP</a>
            </li>
        </ul>

        <a href="https://github.com/upeng" target="_blank" aria-label="view source code">
            <span class="mega-octicon octicon-mark-github" title="GitHub"></span>
        </a>

        <ul class="site-footer-links mobile-hidden">
            
                  
                  <li>
                    <a href="/"  title="Home">Home</a>
                  </li>
            
                  
                  <li>
                    <a href="/categories/"  title="Categories">Categories</a>
                  </li>
            
                  
                  <li>
                    <a href="/bookmark/"  title="Bookmark">Bookmark</a>
                  </li>
            
                  
                  <li>
                    <a href="http://shareup.sinaapp.com"  title="Share">Share</a>
                  </li>
            
                  
                  <li>
                    <a href="/about/"  title="About">About</a>
                  </li>
            
            <li>
                <a href="/atom.xml">
                    <span class="octicon octicon-rss" style="color:orange;"></span>
                </a>
            </li>
        </ul>
    </div>
</footer>


		<script src="/js/geopattern.js"></script>

		
			<script src="/js/toc.js"></script>
		

		<script src="/js/highlight.pack.js"></script>
		<script src="/lib/fancybox/jquery.fancybox-1.3.4.pack.js"></script>

		<script src="/js/index.js"></script>

		 <script src="/js/popular_repo.js"></script> 

	</body>
</html>